import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Divider, Popconfirm, TreeSelect } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { FormattedMessage, useModel } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { setSiteTreeFormat, setTreeFormat, setColumnTreeFormat } from '@/utils';
import { getList, removeField, sysDeptAllTree, cmsSiteAllTree, cmsColumnAllTree } from './api';
import UpdateForm from './components/UpdateForm';
import { values } from 'lodash';

const { SHOW_ALL } = TreeSelect;

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */

const getListData = async fields => {
  const hide = message.loading('加载中');
  try {
    const data = await getList({ ...fields });
    hide();
    if (data && data.code === 0 && data.data.list) {
      return { data: data.data.list, total: data.data.total };
    }
    message.error(data.msg || '请求失败，请重试');
  } catch (error) {
    hide();
    message.error('请求失败，请重试');
    return false;
  }
};

const TableList = () => {
  const actionRef = useRef();
  const [loading, setLoading] = useState(false);

  const [dept, setDept] = useState(); //  部门值
  const [sysDeptAllTreeData, setSysDeptAllTreeData] = useState(); // 部门同步树

  const [site, setSite] = useState(); //  站点
  const [cmsSiteAllTreeData, setcmsSiteAllTreeData] = useState(); // 站点同步树

  const [column, setColumn] = useState(); //  栏目
  const [cmsColumnAllTreeData, setcmsColumnAllTreeData] = useState(); // 栏目同步树

  const { initialState } = useModel('@@initialState');
  const currentDeptId = initialState?.currentUser?.sysUserVo?.deptId;

  const [paylaod, setPallaod] = useState({});

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async id => {
    const hide = message.loading('正在删除');

    try {
      const msg = await removeField(id);
      hide();
      if (msg.code === 0) {
        message.success('删除成功！');
        if (actionRef.current) {
          actionRef.current.reload();
        }
        return true;
      }
      message.error(msg.msg || '删除失败，请重试');
      return false;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  /**
   *  get node
   * @zh-CN 获取部门
   */
  const getDept = () => {
    sysDeptAllTree({ deptId: currentDeptId }).then(res => {
      if (res.code === 0) {
        setSysDeptAllTreeData(setTreeFormat([res.data]));
      }
    });
  };

  /**
   *  get node
   * @zh-CN 获取获取站点
   */
  const getSite = () => {
    cmsSiteAllTree({ siteId: site }).then(res => {
      if (res.code === 0) {
        setcmsSiteAllTreeData(setSiteTreeFormat([res.data]));
      }
    });
  };
  /**
   * @zh-CN 同步获取栏目树
   *
   * @param fields
   */
  const getcmsColumnAllTree = async fields => {
    setLoading(true);
    setColumn(null);
    setcmsColumnAllTreeData([]);
    try {
      const res = await cmsColumnAllTree(fields);
      setLoading(false);
      if (res.code === 0) {
        setcmsColumnAllTreeData(setColumnTreeFormat(res.data));
        return;
      }
      setcmsColumnAllTreeData([]);
    } catch (error) {
      setLoading(false);
      message.error('获取栏目失败，请重试');
      return false;
    }
  };

  const deptOnChange = value => {
    setDept(value);
  };

  // 选择站点
  const siteOnChange = value => {
    setSite(value);
    getcmsColumnAllTree(value);
  };

  // 选择栏目
  const columnOnChange = value => {
    setColumn(value);
  };

  const search = () => {
    const paylaod = {
      deptId: dept,
      siteId: site,
      columnId: column,
      pageSize: 20,
      current: 1,
    };
    setPallaod(paylaod);
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  const reset = () => {
    setDept(null);
    setSite(null);
    setColumn(null);

    const paylaod = {
      pageSize: 20,
      current: 1,
    };
    setPallaod(paylaod);
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  useEffect(() => {
    getDept();
    getSite();
  }, []);

  // 更新数据 组件 ------------------------------------------------------------------

  const [type, setType] = useState();

  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [updataData, setUpdataData] = useState({});

  const [pagination, setPagination] = useState({ current: 1, pageSize: 20 });
  const ProTableOoChange = ({ current, pageSize }) => {
    setPagination({ current, pageSize });
  };

  const closeUpdateForm = () => {
    handleUpdateModalVisible(false);
  };

  const setUpdateForm = (param, index) => {
    setType('updata');
    handleUpdateModalVisible(true);
    setUpdataData(param);
  };

  const updataSuccess = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  // 添加
  const add = () => {
    setType('add');
    setUpdataData({});
    handleUpdateModalVisible(true);
  };
  // ----------------------------------------------结束------------------------------------------------------

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns = [
    {
      title: '序号',
      valueType: 'option',
      dataIndex: '',
      render(text, record, index) {
        return (
          <span key={index}>{(pagination.current - 1) * pagination.pageSize + index + 1}</span>
        );
      },
    },
    {
      title: '栏目名称',
      dataIndex: 'columnName',
    },
    {
      title: '站点',
      dataIndex: 'siteName',
    },
    {
      title: '操作',
      dataIndex: 'opt',
      valueType: 'option',
      render: (_, record, index) => {
        const text = (
          <>
            <Button type="link" onClick={() => setUpdateForm(record, index)}>
              编辑
            </Button>
            <Divider type="vertical" />
            <Popconfirm
              placement="topRight"
              title="确实要删除此条信息吗？"
              onConfirm={() => handleRemove(record.columnId)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="link">删除</Button>
            </Popconfirm>
          </>
        );
        return <>{text}</>;
      },
    },
  ];
  return (
    <PageContainer>
      <div className="g-searchBox">
        部门：
        <TreeSelect
          treeData={sysDeptAllTreeData}
          placeholder="选择部门"
          value={dept}
          showCheckedStrategy={SHOW_ALL}
          style={{ width: 240 }}
          allowClear
          showSearch
          onChange={(value, label, extra) => {
            deptOnChange(value, label, extra);
          }}
        />
        <span style={{ marginLeft: 20 }}>站点：</span>
        <TreeSelect
          treeData={cmsSiteAllTreeData}
          placeholder="选择站点"
          value={site}
          style={{ width: 240 }}
          showSearch
          onChange={(value, label, extra) => {
            siteOnChange(value, label, extra);
          }}
          allowClear
        />
        <span style={{ marginLeft: 20 }}>栏目：</span>
        <TreeSelect
          treeData={cmsColumnAllTreeData}
          placeholder="先选择站点，再选择栏目"
          value={column}
          style={{ width: 240 }}
          showSearch
          onChange={(value, label, extra) => {
            columnOnChange(value, label, extra);
          }}
          allowClear
        />
        <div className="btnBox">
          <Button onClick={reset}>重置</Button>
          <Button type="primary" onClick={search}>
            查询
          </Button>
        </div>
      </div>
      <ProTable
        actionRef={actionRef}
        rowKey={record => record.columnId}
        // search={{
        //   labelWidth: 120,
        // }}
        search={false}
        toolBarRender={() => [
          <Button type="primary" key="primary" onClick={add}>
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        onChange={ProTableOoChange}
        request={() => getListData(paylaod)}
        columns={columns}
      />
      <UpdateForm
        visible={updateModalVisible}
        onCancel={closeUpdateForm}
        data={updataData}
        onSuccess={updataSuccess}
        type={type}
      />
    </PageContainer>
  );
};

export default TableList;
